package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @RequestMapping("/list")
    @ResponseBody
    @RequireLogin
    public Object list(Long id){
        return userInfoService.get(id);
    }


    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){

        return !userInfoService.checkPhone(phone);
    }

    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone){
        AjaxResult result = new AjaxResult();
        //判断验证码是否有效
        String verifyCode = userInfoRedisService.getVerifyCode(phone);
        if (verifyCode != null){
            return result.mark("验证码已发送,请勿重复点击");
        }
        userInfoService.sendVerifyCode(phone);
        return result;
    }


    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone,String nickname,String password,String rpassword,String verifyCode){

        return userInfoService.userRegist(phone,nickname,password,rpassword,verifyCode);
    }


    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(String username, String password, HttpServletResponse response){
        String token = userInfoService.userLogin(username,password);
        CookieUtil.addCookie(response,token,RedisKeys.USER_LOGIN_TOKEN.getTime().intValue(),RedisKeys.USER_LOGIN_TOKEN.join(token));
        return new AjaxResult();
    }

}
